package cn.drenal.capcap.service.impl;

import cn.drenal.capcap.entity.*;
import cn.drenal.capcap.entity.dto.ArtworkSubmitDTO;
import cn.drenal.capcap.entity.vo.ArtworkListVO;
import cn.drenal.capcap.entity.vo.ArtworkDetailVO;
import cn.drenal.capcap.entity.vo.forum.ForumArtworkCardVO;
import cn.drenal.capcap.entity.vo.forum.ForumArtworkDetailVO;
import cn.drenal.capcap.exception.BizException;
import cn.drenal.capcap.mapper.*;
import cn.drenal.capcap.service.ArtworkService;
import cn.drenal.capcap.service.CommentService;
import cn.drenal.capcap.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作品服务实现类
 */
@Service
@RequiredArgsConstructor
public class ArtworkServiceImpl extends ServiceImpl<ArtworkMapper, Artwork> implements ArtworkService {

    private final CategoryMapper categoryMapper;
    private final ArtworkImageMapper artworkImageMapper;
    private final ArtworkTagMapper artworkTagMapper;
    private final TagMapper tagMapper;
    private final ArtworkLikeMapper artworkLikeMapper;
    private final UserService userService;
    private final CommentService commentService;
    private final UserFollowMapper userFollowMapper;
    private final CommentMapper commentMapper;
    private final UserMapper userMapper;
    private final ArtworkFavoriteMapper artworkFavoriteMapper;
    private final ActivityMapper activityMapper;
    private final ActivityVoteMapper activityVoteMapper;

    @Override
    public Artwork createArtwork(Artwork artwork) {
        // 设置初始状态为草稿
        if (artwork.getStatus() == null) {
            artwork.setStatus(0); // 0-草稿
        }
        
        // 初始化计数字段
        artwork.setViewCount(0);
        artwork.setFavoriteCount(0);
        artwork.setCommentCount(0);
        
        // 保存作品
        save(artwork);
        return artwork;
    }

    @Override
    public ArtworkDetailVO getArtworkDetailById(Long id) {
        // 获取作品基本信息
        Artwork artwork = getById(id);
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        
        // // 增加浏览量
        // lambdaUpdate()
        //         .eq(Artwork::getId, id)
        //         .setSql("view_count = view_count + 1")
        //         .update();
        
        // 获取作品图片列表
        LambdaQueryWrapper<ArtworkImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(ArtworkImage::getArtworkId, String.valueOf(id));
        imageWrapper.orderByAsc(ArtworkImage::getSort);
        List<ArtworkImage> images = artworkImageMapper.selectList(imageWrapper);
        
        // 获取作品标签列表
        LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
        tagWrapper.eq(ArtworkTag::getArtworkId, id.toString());
        List<ArtworkTag> artworkTags = artworkTagMapper.selectList(tagWrapper);
        
        List<String> tags = new ArrayList<>();
        if (!artworkTags.isEmpty()) {
            tags = artworkTags.stream()
                    .map(tag -> tagMapper.selectById(tag.getTagId()).getName())
                    .collect(Collectors.toList());
        }
        
        // 构建详情VO
        ArtworkDetailVO detailVO = new ArtworkDetailVO();
        BeanUtils.copyProperties(artwork, detailVO);
        detailVO.setImages(images);
        detailVO.setTags(tags);
        
        // 如果有分类ID，获取分类名称
        if (artwork.getCategoryId() != null) {
            detailVO.setCategoryName(categoryMapper.selectById(artwork.getCategoryId()).getName());
        }
        
        return detailVO;
    }
    
    @Override
    @Transactional
    public Artwork updateArtwork(Long id, Artwork artwork) {
        // 检查作品是否存在
        Artwork existingArtwork = getById(id);
        if (existingArtwork == null) {
            throw new BizException("作品不存在");
        }
        
        // 更新作品信息
        artwork.setId(id);
        updateById(artwork);

        // 处理标签关联，如果有标签数据
        if (artwork.getTags() != null && !artwork.getTags().isEmpty()) {
            // 删除原有标签关联
            LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.eq(ArtworkTag::getArtworkId, id.toString());
            artworkTagMapper.delete(tagWrapper);

            List<String> tagNames = artwork.getTags();
            List<String> tagIds = new ArrayList<>();

            for (String tagName : tagNames) {
                // 查询标签是否已存在
                LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Tag::getName, tagName);
                Tag existingTag = tagMapper.selectOne(queryWrapper);

                if (existingTag != null) {
                    // 标签已存在，使用已有标签ID
                    tagIds.add(existingTag.getId().toString());
                } else {
                    // 标签不存在，创建新标签
                    Tag newTag = new Tag();
                    newTag.setName(tagName);
                    newTag.setStatus(1); // 设置为启用状态
                    tagMapper.insert(newTag);

                    // 使用新创建的标签ID
                    tagIds.add(newTag.getId().toString());
                }
            }
            // 添加新的标签关联
            for (String tagId : tagIds) {
                ArtworkTag artworkTag = new ArtworkTag();
                artworkTag.setArtworkId(id.toString());
                artworkTag.setTagId(tagId);
                artworkTagMapper.insert(artworkTag);
            }
        }
        
        // 处理图片关联，如果有图片数据
        if (artwork.getImages() != null && !artwork.getImages().isEmpty()) {
            // 删除原有图片关联
            LambdaQueryWrapper<ArtworkImage> imageWrapper = new LambdaQueryWrapper<>();
            imageWrapper.eq(ArtworkImage::getArtworkId, id.toString());
            artworkImageMapper.delete(imageWrapper);
            
            // 添加新的图片关联
            for (int i = 0; i < artwork.getImages().size(); i++) {
                ArtworkImage artworkImage = new ArtworkImage();
                artworkImage.setArtworkId(id.toString());
                artworkImage.setImagePath(artwork.getImages().get(i).getImagePath());
                artworkImage.setSort(i);
                
                // 设置封面图
                if (i == 0) {
                    artworkImage.setIsCover(1);
                    // 更新作品封面
                    artwork.setCoverImage(artwork.getImages().get(i).getImagePath());
                    updateById(artwork);
                } else {
                    artworkImage.setIsCover(0);
                }
                
                artworkImageMapper.insert(artworkImage);
            }
        }
        
        return getById(id);
    }

    @Override
    public void deleteArtwork(Long id) {
        // 检查作品是否存在
        if (!lambdaQuery().eq(Artwork::getId, id).exists()) {
            throw new BizException("作品不存在");
        }
        
        // 逻辑删除作品
        removeById(id);
    }

    @Override
    public Artwork getArtworkById(Long id) {
        Artwork artwork = getById(id);
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        return artwork;
    }

    @Override
    public Page<ArtworkListVO> getArtworkPage(Page<ArtworkListVO> page, String title, Integer status, Long categoryId, Long activityId) {
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        Page<Artwork> artworkPage = new Page<>(page.getCurrent(), page.getSize());
        // 添加查询条件
        if (StringUtils.hasText(title)) {
            queryWrapper.like(Artwork::getTitle, title);
        }
        
        if (status != null) {
            queryWrapper.eq(Artwork::getStatus, status);
        }
        
        if (categoryId != null) {
            queryWrapper.eq(Artwork::getCategoryId, categoryId);
        }
        
        // 根据活动ID筛选
        if (activityId != null) {
            queryWrapper.eq(Artwork::getActivityId, activityId);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Artwork::getCreateTime);
        artworkPage = page(artworkPage, queryWrapper);
        page.setRecords(artworkPage.getRecords().stream().map(artwork -> {
            ArtworkListVO vo = new ArtworkListVO();
            User user = userService.getById(artwork.getUserId());
            BeanUtils.copyProperties(artwork, vo);
            vo.setCategoryName(categoryMapper.selectById(artwork.getCategoryId()).getName());
            vo.setUsername(user.getUsername());
            vo.setIsActivity(artwork.getActivityId() == null ? 0 : 1);
            Activity activity = activityMapper.selectById(artwork.getActivityId());
            if (activity != null)
                vo.setActivityName(activity.getName());
            // 获取作品点赞数
            LambdaQueryWrapper<ArtworkLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ArtworkLike::getArtworkId, artwork.getId());
            long likeCount = artworkLikeMapper.selectCount(likeWrapper);
            vo.setLikeCount((int) likeCount);

            // 获取作品投票数
            if (activityId != null) {
                vo.setVoteCount(Math.toIntExact(activityVoteMapper.selectCount(new LambdaQueryWrapper<ActivityVote>()
                        .eq(ActivityVote::getArtworkId, artwork.getId())
                        .eq(ActivityVote::getActivityId, activityId))));
            }

            return vo;
        }).toList());
        return page;
    }

    public Page<ArtworkListVO> getArtworkPage(Page<ArtworkListVO> page, Long categoryId, Long tagId) {
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        Page<Artwork> artworkPage = new Page<>(page.getCurrent(), page.getSize());
        // 添加查询条件


        // 查找已发布的
        queryWrapper.eq(Artwork::getStatus, 2);


        if (categoryId != null) {
            queryWrapper.eq(Artwork::getCategoryId, categoryId);
        }

        // 根据tagID筛选
        if (tagId != null) {
            // 查询包含该标签的作品ID列表
            LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.eq(ArtworkTag::getTagId, tagId.toString());
            List<String> artworkIds = artworkTagMapper.selectList(tagWrapper)
                    .stream()
                    .map(ArtworkTag::getArtworkId)
                    .toList();
            
            // 如果找到包含该标签的作品，则添加ID筛选条件
            if (!artworkIds.isEmpty()) {
                queryWrapper.in(Artwork::getId, artworkIds);
            } else {
                // 如果没有找到包含该标签的作品，返回空结果
                // 通过添加一个不可能满足的条件来实现
                queryWrapper.eq(Artwork::getId, -10086L);
            }
        }


        // 按创建时间降序排序
        queryWrapper.orderByDesc(Artwork::getCreateTime);
        artworkPage = page(artworkPage, queryWrapper);
        page.setRecords(artworkPage.getRecords().stream().map(artwork -> {
            ArtworkListVO vo = new ArtworkListVO();
            User user = userService.getById(artwork.getUserId());
            BeanUtils.copyProperties(artwork, vo);
            vo.setCategoryName(categoryMapper.selectById(artwork.getCategoryId()).getName());
            vo.setUsername(user.getUsername());

            // 获取作品点赞数
            LambdaQueryWrapper<ArtworkLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ArtworkLike::getArtworkId, artwork.getId());
            long likeCount = artworkLikeMapper.selectCount(likeWrapper);
            vo.setLikeCount((int) likeCount);

            return vo;
        }).toList());
        return page;
    }

    @Override
    public Artwork reviewArtwork(Long id, Integer status, String rejectReason) {
        // 检查作品是否存在
        Artwork artwork = getById(id);
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        
        // 检查状态是否有效
        if (status != 2 && status != 3) { // 2-已发布，3-已拒绝
            throw new BizException("无效的审核状态");
        }
        
        // 如果拒绝，必须提供拒绝原因
        if (status == 3 && !StringUtils.hasText(rejectReason)) {
            throw new BizException("拒绝时必须提供拒绝原因");
        }
        
        // 更新状态
        artwork.setStatus(status);
        if (status == 3) {
            artwork.setRejectReason(rejectReason);
        } else {
            artwork.setRejectReason(null);
        }
        
        updateById(artwork);
        return artwork;
    }

    @Override
    public void incrementViewCount(Long id) {
        // 检查作品是否存在
        if (!lambdaQuery().eq(Artwork::getId, id).exists()) {
            throw new BizException("作品不存在");
        }
        
        // 增加浏览量
        lambdaUpdate()
                .eq(Artwork::getId, id)
                .setSql("view_count = view_count + 1")
                .update();
    }

    @Override
    @Transactional
    public Artwork submitArtwork(ArtworkSubmitDTO artworkSubmitDTO, Long userId) {
        // 创建作品
        Artwork artwork = new Artwork();
        BeanUtils.copyProperties(artworkSubmitDTO, artwork);
        artwork.setStatus(1); // 设置为审核中状态
        artwork.setUserId(userId);
        // 保存作品
        save(artwork);
        
        // 保存作品图片
        if (artworkSubmitDTO.getImages() != null && !artworkSubmitDTO.getImages().isEmpty()) {
            for (int i = 0; i < artworkSubmitDTO.getImages().size(); i++) {
                ArtworkImage artworkImage = new ArtworkImage();
                artworkImage.setArtworkId(artwork.getId().toString());
                artworkImage.setImagePath(artworkSubmitDTO.getImages().get(i).getImagePath());
                artworkImage.setSort(i);
                
                // 设置第一张图片为封面
                if (i == 0) {
                    artworkImage.setIsCover(1);
                    // 更新作品封面
                    artwork.setCoverImage(artworkSubmitDTO.getImages().get(i).getImagePath());
                    updateById(artwork);
                } else {
                    artworkImage.setIsCover(0);
                }
                
                artworkImageMapper.insert(artworkImage);
            }
        }
        
        // 保存作品标签
        if (artworkSubmitDTO.getTags() != null && !artworkSubmitDTO.getTags().isEmpty()) {
            for (String tagId : artworkSubmitDTO.getTags()) {
                ArtworkTag artworkTag = new ArtworkTag();
                artworkTag.setArtworkId(artwork.getId().toString());
                artworkTag.setTagId(tagId);
                artworkTagMapper.insert(artworkTag);
            }
        }
        
        return artwork;
    }

    @Override
    public Page<ForumArtworkCardVO> getLatestArtworks(Page<Artwork> page) {
        LambdaQueryWrapper<Artwork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Artwork::getStatus, 2); // 只查询已发布的作品
        wrapper.orderByDesc(Artwork::getCreateTime);

        Page<ForumArtworkCardVO> forumArtworkCardVOPage = new Page<>(page.getCurrent(), page.getSize());
        page = page(page, wrapper);

        List<ForumArtworkCardVO> forumArtworkCardVOList = page.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setUserId(user.getId());
            }
            vo.setCommentCount(artwork.getCommentCount());
            vo.setFavoriteCount(artwork.getFavoriteCount());
            vo.setComprehensiveScore(artwork.getCommentCount() + artwork.getFavoriteCount() * 10);
            return vo;
        }).toList();

        BeanUtils.copyProperties(page, forumArtworkCardVOPage);
        forumArtworkCardVOPage.setRecords(forumArtworkCardVOList);

        return forumArtworkCardVOPage;
    }
    
    @Override
    public List<ForumArtworkCardVO> getTopArtworksByCommentCount(int limit) {
        // 查询所有已发布的作品
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getStatus, 2); // 只查询已发布的作品
        queryWrapper.orderByDesc(Artwork::getCommentCount); // 按评论数倒序
        queryWrapper.last("LIMIT " + limit); // 限制数量
        List<Artwork> artworks = list(queryWrapper);
        
        // 转换为VO对象
        return artworks.stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            vo.setId(artwork.getId());
            vo.setTitle(artwork.getTitle());
            vo.setCoverImage(artwork.getCoverImage());
            
            // 获取作者信息
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setUserId(user.getId());
            }
            
            // 设置评论数和收藏数
            vo.setCommentCount(artwork.getCommentCount());
            vo.setFavoriteCount(artwork.getFavoriteCount());
            
            // 计算综合评分
            vo.setComprehensiveScore(artwork.getCommentCount() + artwork.getFavoriteCount() * 10);
            
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ForumArtworkCardVO> getTopArtworksByFavoriteCount(int limit) {
        // 查询所有已发布的作品
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getStatus, 2); // 只查询已发布的作品
        queryWrapper.orderByDesc(Artwork::getFavoriteCount); // 按收藏数倒序
        queryWrapper.last("LIMIT " + limit); // 限制数量
        List<Artwork> artworks = list(queryWrapper);
        
        // 转换为VO对象
        return artworks.stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            vo.setId(artwork.getId());
            vo.setTitle(artwork.getTitle());
            vo.setCoverImage(artwork.getCoverImage());
            
            // 获取作者信息
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setUserId(user.getId());
            }
            
            // 设置评论数和收藏数
            vo.setCommentCount(artwork.getCommentCount());
            vo.setFavoriteCount(artwork.getFavoriteCount());
            
            // 计算综合评分
            vo.setComprehensiveScore(artwork.getCommentCount() + artwork.getFavoriteCount() * 10);
            
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ForumArtworkCardVO> getTopArtworksByComprehensiveScore(int limit) {
        // 查询所有已发布的作品
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getStatus, 2); // 只查询已发布的作品
        List<Artwork> artworks = list(queryWrapper);
        
        // 转换为VO对象并计算综合评分
        List<ForumArtworkCardVO> result = artworks.stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            vo.setId(artwork.getId());
            vo.setTitle(artwork.getTitle());
            vo.setCoverImage(artwork.getCoverImage());
            
            // 获取作者信息
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
                vo.setUserId(user.getId());
            }
            
            // 设置评论数和收藏数
            vo.setCommentCount(artwork.getCommentCount());
            vo.setFavoriteCount(artwork.getFavoriteCount());
            
            // 计算综合评分（评论数 + 收藏数*10）
            vo.setComprehensiveScore(artwork.getCommentCount() + artwork.getFavoriteCount() * 10);
            
            return vo;
        }).collect(Collectors.toList());
        
        // 按综合评分排序并限制数量
        return result.stream()
                .sorted(Comparator.comparing(ForumArtworkCardVO::getComprehensiveScore).reversed())
                .limit(limit)
                .collect(Collectors.toList());
    }

    @Override
    public Page<Artwork> getHelpArtworks(Page<Artwork> page) {
        // 获取带有萌新求助标签的作品ID列表
        LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
        tagWrapper.eq(ArtworkTag::getTagId, "-1"); // 萌新求助标签的ID为-1
        List<String> artworkIds = artworkTagMapper.selectList(tagWrapper)
                .stream()
                .map(ArtworkTag::getArtworkId)
                .toList();
        
        if (artworkIds.isEmpty()) {
            return page;
        }
        
        // 查询作品信息
        LambdaQueryWrapper<Artwork> artworkWrapper = new LambdaQueryWrapper<>();
        artworkWrapper.in(Artwork::getId, artworkIds)
                .eq(Artwork::getStatus, 2) // 只查询已发布的作品
                .orderByDesc(Artwork::getCreateTime);
        
        return page(page, artworkWrapper);
    }

    @Override
    public ForumArtworkDetailVO getForumArtworkDetail(Long id, Long userId) {
        // 获取作品基本信息
        ArtworkDetailVO artworkDetail = getArtworkDetailById(id);
        
        // 构建详情VO
        ForumArtworkDetailVO detailVO = new ForumArtworkDetailVO();
        BeanUtils.copyProperties(artworkDetail, detailVO);
        
        // 获取作品标签
        LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
        tagWrapper.eq(ArtworkTag::getArtworkId, id.toString());
        List<ArtworkTag> artworkTags = artworkTagMapper.selectList(tagWrapper);
        
        List<String> tags = new ArrayList<>();
        if (!artworkTags.isEmpty()) {
            tags = artworkTags.stream()
                    .map(tag -> {
                        Tag tagEntity = tagMapper.selectById(tag.getTagId());
                        return tagEntity != null ? tagEntity.getName() : null;
                    })
                    .filter(tag -> tag != null)
                    .collect(Collectors.toList());
        }
        detailVO.setTags(tags);
        
        // 获取作者信息
        User author = userService.getById(artworkDetail.getUserId());
        if (author != null) {
            detailVO.setUserId(author.getId());
            detailVO.setUsername(author.getUsername());
            detailVO.setUserAvatar(author.getAvatar());
            detailVO.setUserBio(author.getBio());
            
            // 获取作者粉丝数
            LambdaQueryWrapper<UserFollow> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.eq(UserFollow::getFollowingId, author.getId());
            long followerCount = userFollowMapper.selectCount(followWrapper);
            detailVO.setFollowerCount((int) followerCount);
            
            // 获取作品点赞数
            LambdaQueryWrapper<ArtworkLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ArtworkLike::getArtworkId, id);
            long likeCount = artworkLikeMapper.selectCount(likeWrapper);
            detailVO.setLikeCount((int) likeCount);

            // 获取作品收藏数
            LambdaQueryWrapper<ArtworkFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(ArtworkFavorite::getArtworkId, id);
            long favoriteCount = artworkFavoriteMapper.selectCount(favoriteWrapper);
            detailVO.setFavoriteCount((int) favoriteCount);
            
            // 获取作者作品数
            LambdaQueryWrapper<Artwork> artworkWrapper = new LambdaQueryWrapper<>();
            artworkWrapper.eq(Artwork::getUserId, author.getId())
                    .eq(Artwork::getStatus, 2); // 只统计已发布的作品
            long artworkCount = count(artworkWrapper);
            detailVO.setArtworkCount((int) artworkCount);
        }
        
        // 获取评论列表
        Page<Comment> commentPage = new Page<>(1, 10);
        LambdaQueryWrapper<Comment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(Comment::getArtworkId, id)
                .eq(Comment::getStatus, 1) // 只查询已审核的评论
                .isNull(Comment::getParentId) // 只查询一级评论
                .orderByDesc(Comment::getCreateTime);
        Page<Comment> comments = commentService.page(commentPage, commentWrapper);
        detailVO.setComments(comments.getRecords());
        
        // 判断当前用户是否点赞
        if (userId != null) {
            LambdaQueryWrapper<ArtworkLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ArtworkLike::getUserId, userId)
                    .eq(ArtworkLike::getArtworkId, id);
            boolean isLiked = artworkLikeMapper.selectCount(likeWrapper) > 0;
            detailVO.setIsLiked(isLiked);
            
            // 判断当前用户是否收藏
            LambdaQueryWrapper<ArtworkFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(ArtworkFavorite::getUserId, userId)
                    .eq(ArtworkFavorite::getArtworkId, id);
            boolean isFavorite = artworkFavoriteMapper.selectCount(favoriteWrapper) > 0;
            detailVO.setIsFavorite(isFavorite);
        } else {
            detailVO.setIsLiked(false);
            detailVO.setIsFavorite(false);
        }
        
        return detailVO;
    }

    @Override
    public boolean toggleArtworkLike(Long artworkId, Long userId) {
        // 检查作品是否存在
        Artwork artwork = getById(artworkId);
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        
        // 检查是否已点赞
        LambdaQueryWrapper<ArtworkLike> likeWrapper = new LambdaQueryWrapper<>();
        likeWrapper.eq(ArtworkLike::getUserId, userId)
                .eq(ArtworkLike::getArtworkId, artworkId);
        ArtworkLike like = artworkLikeMapper.selectOne(likeWrapper);
        
        if (like != null) {
            // 已点赞，取消点赞
            artworkLikeMapper.deleteById(like.getId());
            
            // 减少点赞数
            lambdaUpdate()
                    .eq(Artwork::getId, artworkId)
                    .setSql("favorite_count = favorite_count - 1")
                    .update();
            
            return false; // 返回未点赞状态
        } else {
            // 未点赞，添加点赞
            like = new ArtworkLike();
            like.setUserId(userId);
            like.setArtworkId(artworkId);
            artworkLikeMapper.insert(like);
            
            // 增加点赞数
            lambdaUpdate()
                    .eq(Artwork::getId, artworkId)
                    .setSql("favorite_count = favorite_count + 1")
                    .update();
            
            return true; // 返回已点赞状态
        }
    }

    @Override
    public Integer getLikeCount(Long artworkId) {
        return Math.toIntExact(artworkLikeMapper.selectCount(new LambdaQueryWrapper<ArtworkLike>().eq(ArtworkLike::getArtworkId, artworkId)));
    }

    @Override
    public Page<ForumArtworkCardVO> getRecommendedArtworks(Page<Artwork> page) {
        // 创建结果页对象
        Page<ForumArtworkCardVO> resultPage = new Page<>();
        
        // 查询已发布的作品
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getStatus, 2); // 只查询已发布的作品
        Page<Artwork> artworkPage = page(page, queryWrapper);
        
        // 转换为VO对象并获取真实点赞数
        List<ForumArtworkCardVO> records = artworkPage.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            
            // 设置作者名称
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            // 获取真实点赞数
            vo.setLikeCount(getLikeCount(artwork.getId()));
            
            return vo;
        }).collect(Collectors.toList());
        
        // 按点赞数降序排序
        records.sort((a, b) -> b.getLikeCount().compareTo(a.getLikeCount()));
        
        // 设置分页信息
        BeanUtils.copyProperties(artworkPage, resultPage, "records");
        resultPage.setRecords(records);
        
        return resultPage;
    }

}